package controllers;

import java.awt.event.ActionEvent;
import java.sql.Array;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Vector;

import javax.swing.JOptionPane;

import models.CustomTable;
import models.CustomTableModel;
import models.CustomerPurchaseModel;

import dialogs.CreditCardDialog;
import dialogs.InStorePurchaseDialog;

import system.View;

public class InStorePurchaeController extends CustomerPurchaseController {

	private String sname;
	
	public InStorePurchaeController(View v) {
		super(v);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String actionCommand = e.getActionCommand();
		if (actionCommand.equals("Process Purchase"))
			showDialogWindow(new InStorePurchaseDialog(view, actionCommand,
					"Key", new String[] { "Store Name: ", "Item UPC: ", "Quantity: " }, this));
	}

	@Override
	public int validateInsert(Vector<String> s) {
		String actionCommand = s.remove(s.size()-1);
		int retCode = validateEntries(s);		
		if (retCode == OPERATIONSUCCESS)
		{
			System.out.println("\nUPC     Quantity");
			System.out.println("---     --------");
			//TODO: Need to calculate the total price to be paid 
			for (Vector<String> single_item : full_purchase)
				System.out.println(single_item.get(1) + "     " + single_item.get(2));
			if (actionCommand.equals("Pay Credit")) showDialogWindow(new CreditCardDialog(view, this));
			else finalizeTransaction(null);
			return OPERATIONSUCCESS;
		}
		else return retCode;
	}

	@Override
	public int finalizeTransaction(Vector<String> s){
		
		if (s != null)
		{
			if (s.size() != 2)
				return VALIDATIONERROR;
			
			String card_no;
			Date expire_date;
			
			try {
				if (s.get(0).length() != 0)
					card_no = s.get(0).trim();
				else return VALIDATIONERROR;
				
				SimpleDateFormat fm = new SimpleDateFormat("MM/yy");
		
				if (s.get(1).length() != 0)
					expire_date = new Date(fm.parse(s.get(1).trim()).getTime());
				else return VALIDATIONERROR;
			} 
			catch(NumberFormatException ex) { return VALIDATIONERROR; }
			catch (ParseException ex) { return VALIDATIONERROR; }
			customer_purchase.setCardInfo(card_no, expire_date);
		}
		else //Means customer is paying by cash
			customer_purchase.setCardInfo(null, null);
		
		int upc;
		int quantity;
		CustomerPurchaseModel.setCID(null); //In-store purchase doesn't contain cid
		sname = full_purchase.get(0).get(0).trim();
		for (int i=0; i<full_purchase.size(); i++)
		{
			Vector<String> single_item = full_purchase.get(i);
			upc = Integer.valueOf(single_item.get(1).trim());
			quantity = Integer.valueOf(single_item.get(2).trim());
			if (!customer_purchase.processPurchase(sname, upc, quantity))
				return operationFailure();
		}
		
		ResultSet rs1 = customer_purchase.printReceipt();
		ResultSet rs2 = customer_purchase.printReceipt();
		int receiptId;
		
		if ( (receiptId =customer_purchase.commit()) != -1) {
			full_purchase.clear();
			
			CustomTableModel model = new CustomTableModel(customer_purchase.getConnection(), rs1);
			CustomTable data = new CustomTable(model);
		
			model.addExceptionListener(this);
			data.addExceptionListener(this);
			view.addTable(data);
			
			try {
				int total = 0;
				while (rs2.next()) total += rs2.getInt(4);
				JOptionPane.showMessageDialog(view, "Your total price is: $" + total + 
						                            "\nReceipt ID: " + receiptId, "Total",
						JOptionPane.INFORMATION_MESSAGE);
			} catch (SQLException e) { e.printStackTrace(); }
			
			return operationSuccess();
		}
		else return operationFailure();
	}
	
	@Override
	public int validateEntries(Vector<String> s) {
		if (s.size() != 3)
			return VALIDATIONERROR;

		String sname;
		int upc;
		int quantity;
		try {
			//If all fields are empty, don't give an error
			//Maybe user made a mistake and added item unnecessarily
			if (full_purchase.size() != 0 && s.get(1).trim().length() == 0 && s.get(2).trim().length() == 0) 
				return OPERATIONSUCCESS;
			
			if (s.get(0).length() != 0)
				sname = s.get(0).trim();
			else return VALIDATIONERROR;
			if (s.get(1).length() != 0)
				upc = Integer.valueOf(s.get(1).trim());
			else return VALIDATIONERROR;
			if (s.get(2).length() != 0)
				quantity = Integer.valueOf(s.get(2).trim());
			else return VALIDATIONERROR;
			
			//Don't allow zero or negative quantity
			if (quantity < 1) return VALIDATIONERROR;
			
			//If item has already been added to basket, don't let user add it again
			for (Vector<String> entry : full_purchase)
				if (Integer.parseInt(entry.get(1).trim()) == upc)
					return VALIDATIONERROR;
			
			if (!customer_purchase.isQuantityEnough(sname, upc, quantity)) 
				return OPERATIONFAILED;
		} catch (NumberFormatException ex) {
			return OPERATIONFAILED;
		}
		full_purchase.add(s);
		return OPERATIONSUCCESS;
	}
	
	@Override
	public void show() {
		// TODO Auto-generated method stub
	}

	@Override
	public int validateDelete(Vector<String> s) {
		// TODO Auto-generated method stub
		return 0;
	}
}
